<template>
  <el-dialog title="邮箱api" width="30%" destroy-on-close :visible.sync="emailApi" @close="onClose">
    <el-form ref="form" :model="form" label-width="100px" class="demo-dynamic">
      <el-form-item prop="link" label="链接">
        <el-input v-model="form.link" />
      </el-form-item>
      <el-form-item label="上传txt">
        <input id="files" type="file" style="display:none" accept=".txt" @change="handleFileUpload">
        <el-button type="primary" @click="clickBtn">上传txt</el-button>
        <div v-if="fileName">
          <i class="el-icon-notebook-2" />
          <span>{{ fileName }}</span>
        </div>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button :loading="loading" @click="handleeviceCacel('form')">取 消</el-button>
      <el-button type="primary" :loading="loading" @click="submitForm('form')">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  data() {
    return {
      emailApi: false,
      fileName: '',
      loading: false,
      form: {
        link: ''
      },
      txt: ''
    }
  },
  methods: {
    open() {
      this.$http.get('/api/cloud_data/email/api/get').then(res => {
        this.form.link = res.data
      })
      this.emailApi = true
    },
    // 新建树弹窗取消
    handleeviceCacel() {
      this.emailApi = false
    },
    onClose() {
      this.$refs.form.resetFields({})
      this.loading = false
    },
    clickBtn() {
      const inp = document.getElementById('files')
      inp.click()
    },
    handleFileUpload(event) {
      const file = event.target.files[0]
      const reader = new FileReader()
      this.fileName = file.name || ''
      reader.onload = () => {
        const fileContent = reader.result
        // 处理换行符
        const lines = fileContent.split(/\r?\n/)
        // 对每行内容进行处理
        lines.forEach(line => {
          console.log(line)
          line += line + '\n'
        })
        this.txt = lines.join('')
      }

      reader.readAsText(file)
    },
    submitForm() {
      this.loading = true
      this.$http.get(`/api/cloud_data/email/insert?url=${this.form.link}&text=${this.txt}`).then(res => {
        if (res.success) {
          this.emailApi = false
          this.$success('操作成功')
          this.loading = false
        } else {
          this.loading = false
          this.$error(res.msg)
        }
      })
      // this.$refs[formName].validate(valid => {
      //   if (valid) {
      //     this.emailApi = false;
      //   } else {
      //     console.log("error submit!!");
      //     return false;
      //   }
      // });
    }

  }
}
</script>

<style scoped>
.dialog-footer {
  text-align: center;
}
</style>
